package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: dw
 * @Date 2022/3/16 18:55
 */
@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Autowired(required = false)
    private SetmealDishMapper setmealDishMapper;

    @Autowired(required = false)
    private HttpSession session;

    /**
     * 分页查询套餐
     *
     * @param page 当前页
     * @param pageSize 每页数据
     * @param name 按名称条件模糊查询
     * @return
     */
    @Override
    public Page<SetmealDto> findAllByPage(Integer page, Integer pageSize, String name) {
        //设置当前页和每页数据
        PageHelper.startPage(page,pageSize);
        //调用mapper查询
        List<SetmealDto> setmealDtoList = setmealMapper.findAllByPage(name);
        //封装成PageInfo
        PageInfo<SetmealDto> pageInfo = new PageInfo<>(setmealDtoList);

        //封装成Page
        Page<SetmealDto> pageObj = new Page<>();
        pageObj.setRecords(pageInfo.getList());
        pageObj.setTotal(pageInfo.getTotal());

        return pageObj;
    }

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @Override
    @Transactional
    public boolean save(SetmealDto setmealDto) {
        //判断新增套餐是否存在
        if (setmealMapper.findByName(setmealDto)!=null) {
            throw new BusinessException("该套餐已存在，请重新添加");
        }
        //获取会话域的id
        Long id = (Long) session.getAttribute("employee");
        //补全套餐数据
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setCreateUser(id);
        setmealDto.setUpdateUser(id);

        //调用mapper层添加
        setmealMapper.save(setmealDto);

        //补全菜品信息
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes().stream().map((setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateTime(setmealDto.getCreateTime());
            setmealDish.setUpdateTime(setmealDto.getUpdateTime());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setSort(0);
            return setmealDish;
        })).collect(Collectors.toList());

        //调用mapper添加
        setmealDishMapper.save(setmealDishList);

        return true;
    }

    /**
     * 批量修改状态
     *
     * @param status
     * @param ids
     */
    @Override
    public boolean updateStatus(Integer status, List<Long> ids) {
        setmealMapper.updateStatus(status, ids);
        return true;
    }

    /**
     * 回显页面
     *
     * @param id
     * @return
     */
    @Override
    public SetmealDto findBySetmealId(Long id) {
        return setmealMapper.findBySetmealId(id);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @Override
    @Transactional
    public boolean updateSetmeal(SetmealDto setmealDto) {
        //判断新增套餐是否存在
        Setmeal dbSetmealDto = setmealMapper.findByName(setmealDto);
        if (dbSetmealDto!=null && !setmealDto.getId().equals(dbSetmealDto.getId())) {
            throw new BusinessException("该套餐已存在，请重新输入");
        }
        //获取会话域的id
        Long id = (Long) session.getAttribute("employee");
        //补全套餐数据
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setCreateUser(id);
        setmealDto.setUpdateUser(id);

        //调用mapper层添加
        setmealMapper.updateSetmeal(setmealDto);
        //删除关联的菜品
        setmealDishMapper.delete(setmealDto.getId());

        //补全菜品信息
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes().stream().map((setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateTime(setmealDto.getCreateTime());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setSort(0);
            return setmealDish;
        })).collect(Collectors.toList());

        //调用mapper添加
        setmealDishMapper.save(setmealDishList);

        return true;
    }

    /**
     * 根据套餐id删除套餐（伪删除）
     *
     * @param ids
     * @return
     */
    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public boolean deleteSetmeals(List<Long> ids) {
        //判断该套餐是否为起售状态，起售状态不允许删除
        Integer count = setmealMapper.countByIds(ids);
        if (count>0) {
            throw new BusinessException("该套餐起售状态，无法被删除");
        }
        //获取会话域中的id
        Long id = (Long) session.getAttribute("employee");
        //删除套餐下的菜品
        setmealDishMapper.deleteByIds(ids,LocalDateTime.now(),id);
        //删除套餐
        setmealMapper.deleteByIds(ids,LocalDateTime.now(),id);
        return true;
    }

    /**
     * 根据套餐id和状态码查询所有套餐
     *
     * @param categoryId
     * @param status
     * @return
     */
    /**
     * 根据条件查询套餐数据
     * @param categoryId
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status",unless = "#resule==null")
    @Override
    public List<SetmealDto> findCategoryIdAndStatus(Long categoryId, Integer status) {
        List<SetmealDto> setmealDtoList = setmealMapper.findCategoryIdAndStatus(categoryId, status);
        return setmealDtoList;
    }


}
